package com.mask.token.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mask.token.common.Result;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 访问拒绝处理器
 * 处理已认证但无权限的请求
 *
 * @author mask
 * @since 1.0.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MaskAccessDeniedHandler implements AccessDeniedHandler {

    private final ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                      AccessDeniedException accessDeniedException) throws IOException, ServletException {
        
        log.warn("访问被拒绝: {} {}, 原因: {}", 
                request.getMethod(), request.getRequestURI(), accessDeniedException.getMessage());
        
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        
        Result<Object> result = Result.fail(403, "访问被拒绝，权限不足");
        
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}
